package jjn.carl.string;

/**
 * @author Jjn
 * @since 2023/7/5 16:41
 */
public class LeetCode541 {
    public String reverseStr(String s, int k) {
        StringBuilder stringBuilder = new StringBuilder();
        int left = 0, right = 0;
        while (left < s.length() && right < s.length()) {
            right = left + k - 1;
            for (int i = Math.min(right, s.length() - 1); i >= left; i--) {
                stringBuilder.append(s.charAt(i));
            }
            left = right + 1;
            right = left + k - 1;
            for (int i = left; i <= Math.min(right, s.length() - 1); i++) {
                stringBuilder.append(s.charAt(i));
            }
            left = right + 1;
        }
        return stringBuilder.toString();
    }
    
    public static void main(String[] args) {
        // 如果剩余字符少于 k 个，则将剩余字符全部反转。
        // 如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。
        // bacdfeg
        System.out.println("new LeetCode541().reverseStr(\"abcdefg\", 2) = " + new LeetCode541().reverseStr("abcdefg", 2));
        // bacd
        System.out.println("new LeetCode541().reverseStr(\"abcd\", 2) = " + new LeetCode541().reverseStr("abcd", 2));
    }
}
